﻿using SSC.Models;
using SSC.Services;
using System.IO;
using System.Windows;
using System.Windows.Controls;

namespace SSC.Views
{
    /// <summary>
    /// wdRecord.xaml 的交互逻辑
    /// </summary>
    public partial class wdRecord : Window
    {
        private OperationLogService _logService = new();
        public wdRecord()
        {
            InitializeComponent();
        }
        // 查询按钮点击事件
        private void BtnQuery_Click(object sender, RoutedEventArgs e)
        {
            DateTime? start = dpStartDate.SelectedDate;
            DateTime? end = dpEndDate.SelectedDate;

            // 获取操作类型（ComboBoxItem 的 Content）
            string? type = (cbOperationType.SelectedItem as ComboBoxItem)?.Content?.ToString();

            // 获取所有日志
            List<LogModel> logs = _logService.GetLogs(start, end);

            // 如果不是“全部”，就进一步筛选
            if (type != "全部")
            {
                logs = logs.Where(l => l.OperationType == type).ToList();
            }

            // 显示到表格
            dgLogs.ItemsSource = logs;
        }
        // 导出按钮点击事件（示例使用 CSV 导出）
        private void BtnExport_Click(object sender, RoutedEventArgs e)
        {
            if (dgLogs.ItemsSource is not List<LogModel> logs || logs.Count == 0)
            {
                MessageBox.Show("没有可导出的记录！");
                return;
            }

            // 简单写个 CSV 文件
            Microsoft.Win32.SaveFileDialog dlg = new()
            {
                FileName = "操作记录",
                DefaultExt = ".csv",
                Filter = "CSV 文件 (*.csv)|*.csv"
            };

            if (dlg.ShowDialog() == true)
            {
                try
                {
                    using var writer = new StreamWriter(dlg.FileName);
                    writer.WriteLine("时间,用户,操作类型,详情");

                    foreach (var log in logs)
                    {
                        string line = $"{log.DateTime},{log.UserName},{log.OperationType},{log.Description}";
                        writer.WriteLine(line);
                    }

                    MessageBox.Show("导出成功！");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("导出失败：" + ex.Message);
                }
            }
        }
    }
}
